package com.wang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.mapper.AttentionMapper;
import com.wang.mapper.CourseResourceMapper;
import com.wang.pojo.Attention;
import com.wang.pojo.Course;
import com.wang.pojo.CourseDTO;
import com.wang.pojo.CourseResource;
import com.wang.response.Result;
import com.wang.response.ResultResponse;
import com.wang.service.CourseService;
import com.wang.mapper.CourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 */
@Service
@Transactional
public class CourseServiceImpl
    implements CourseService{
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    CourseResourceMapper resourceMapper;
    @Autowired
    AttentionMapper attentionMapper;

    @Override
    public ResultResponse addCourse(CourseDTO courseDTO) {
        Course course = courseDTO.getCourse();
        courseMapper.insert(course);
        List<String> resource = courseDTO.getResource();
        for (String s : resource) {
            CourseResource courseResource = new CourseResource();
            courseResource.setCourseId(course.getCourseId());
            courseResource.setResourceUrl(s);
            resourceMapper.insert(courseResource);
        }
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse addAttention(Attention attention) {
        Integer count =attentionMapper.doYouAttention(attention.getSpecialistId(),attention.getUserId());
        //是否取关过
        if(count>0){
            attentionMapper.addAttention(attention.getSpecialistId(),attention.getUserId());
            return ResultResponse.SUCCESS();
        }
        attentionMapper.insert(attention);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse cancelAttention(Attention attention) {
        attentionMapper.cancelAttention(attention);
        return ResultResponse.SUCCESS();
    }

    @Override
    public ResultResponse searchCourse(Integer pageNum, Integer pageSize) {
        Page<Course> page = new Page<>();
        Page<Course> page1 = courseMapper.selectPage(page, null);
        List<Course> records = page1.getRecords();
        for (Course record : records) {
            Integer courseId = record.getCourseId();
            List<CourseResource> courseResources = resourceMapper.selectList(new QueryWrapper<CourseResource>().lambda().eq(CourseResource::getCourseId, courseId));
            record.setResourceList(courseResources);
        }
        return ResultResponse.SUCCESS(records,page1.getTotal());
    }


}




